const userUtils = require("../../utils/user");
const validate = require('../../utils/validate')
const common = require('../../utils/common')
const { queryOrderBPage } = require('../../services/order')
const dayjs = require('../../utils/dayjs')
const startTime = dayjs().startOf('month').format('YYYY-MM-DD')
const endTime = dayjs().format('YYYY-MM-DD')
const formatShowDate = (date) => {
  return dayjs(date).format('YYYY年MM月DD日')
}
const defaultPage = {
  curPage: 1,
  pageSize: 10,
}
Page({
  data: {
    total: 10,
    query: {
      ...defaultPage,
      searchNo: '',
      startTime,
      endTime,
    },
    dateRange: {
      startTime: formatShowDate(startTime),
      endTime: formatShowDate(endTime),
    },
    orderList: [],
  },
  onLoad: function ({ searchNo }) {
    this.queryChange({ searchNo })
  },
  queryChange: function (payload) {
    this.setData({
      query: { ...this.data.query, ...payload }
    }, this.getOrderList)
  },
  getOrderList: function () {
    if (this.data.query.curPage > 1 && this.data.orderList.length >= this.data.total) return
    const params = { ...this.data.query }
    queryOrderBPage(params).then(res => {
      const { total } = res.page
      this.setData({ total })
      if (params.curPage == 1) {
        this.setData({
          orderList: res.data
        })
      } else {
        this.setData({
          orderList: [...this.data.orderList, ...res.data]
        })
      }

    })
  },
  scrollBottom: function () {
    const curPage = ++this.data.query.curPage
    this.queryChange({ curPage })
  },
  formatShowDate(date) {
    return dayjs(date).format('YYYY年MM月DD日')
  },
  //开始时间
  onBeginChange: function (e) {
    const startTime = e.detail.value
    this.queryChange({ startTime, ...defaultPage })
    this.setData({
      dateRange: { ...this.data.dateRange, startTime: formatShowDate(startTime) }
    })
  },
  onEndChange: function (e) {
    const endTime = e.detail.value
    this.queryChange({ endTime, ...defaultPage })
    this.setData({
      dateRange: { ...this.data.dateRange, endTime: formatShowDate(endTime) }
    })
  },
  openSearchOrder: function (e) {
    wx.navigateTo({ url: '/pages/search-order/index?type=1' })
  },
  cancelSearch: function () {
    this.queryChange({ searchNo: '', ...defaultPage })
  },
  goDetail: function (e) {
    const { index } = e.currentTarget.dataset;
    const item = this.data.orderList[index];
    wx.navigateTo({ url: `/pages/order-info/index?id=${item.orderId}` })
  },
  makePhoneCall: function (e) {
    const { phone } = e.currentTarget.dataset;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  goSell: function (e) {
    const { index } = e.currentTarget.dataset
    const item = this.data.orderList[index]
    wx.navigateTo({ url: `/pages/request-sell-service/index?id=${item.orderId}` })
  }
})
